package com.huarui.permission.inteceptor;

import java.util.Properties;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

import com.huarui.permission.dataobject.Action;
import com.huarui.permission.service.ActionService;
import com.huarui.permission.service.PermissionService;
import com.huarui.user.security.UserHolder;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;


@Deprecated
public class CorpAuthenticationInterceptor extends AbstractInterceptor {
	
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 9065698360163865871L;
	private PermissionService  permissionService;
	
	private Properties  env;
	
	private ActionService actionService;
	

	public ActionService getActionService() {
		return actionService;
	}



	public void setActionService(ActionService actionService) {
		this.actionService = actionService;
	}



	public Properties getEnv() {
		return env;
	}



	public void setEnv(Properties env) {
		this.env = env;
	}



	public PermissionService getPermissionService() {
		return permissionService;
	}



	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}



	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		final String action=invocation.getProxy().getActionName();
		final String method = invocation.getProxy().getMethod();
		
		Integer  companyId = UserHolder.getCurrentSessionMessage().getCompanyId();
		
		if(companyId==0){
			/**
			 * 该用户未注册公司也不属于任何公司
			 */
			Object obj= CollectionUtils.find(permissionService.getActionsGranted2LoginedUser(), new Predicate() {
				
				@Override
				public boolean evaluate(Object object) {
					Action a = (Action) object;
					return a.getActionName().equalsIgnoreCase(action)  &&  a.getMethodName().equalsIgnoreCase(method);
				}
			});
			
			if(obj==null){
				/**
				 * 无公司用户不允许访问该url , 跳转到注册公司页面
				 */
				return env.getProperty("registCorpUrl", "http://www.uec3.com/myweb/company/");
			}
			
			return invocation.invoke();
			
		}
	    
		Integer  permissionId = actionService.getPermissionId(action, method);
		
		if(permissionId==null){
			/**
			 * 不需要权限控制
			 */
			return invocation.invoke();
		}
		
		if ( permissionService.hasPermission(permissionId) == 0) {
			
			return env.getProperty("orderServiceUrl","http://localhost:8080/myweb/");
			
		}
		
		
		
		return invocation.invoke();
	}

}
